package com.terabits.smartriver.controller;

import com.terabits.smartriver.meta.po.Log;
import com.terabits.smartriver.meta.po.User;
import com.terabits.smartriver.service.LogService;
import com.terabits.smartriver.service.UserService;
import com.terabits.smartriver.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.terabits.smartriver.util.HttpUtils.getIpAddress;

/**
 * Created by Yin on 2019/3/6
 */
public class BaseController {
    /**
     * 日志类型
     */
    //用户登陆日志
    public static final Integer LOG_TYPE_USERLOGIN = 0;
    //用户操作日志
    public static final Integer LOG_TYPE_USER = 1;
    //其他日志
    public static final Integer LOG_TYPE_OTHER = -1;

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    public void addLog(Integer type, String title, String content) {

        User currentUser = findCurrentUser();
        Log log = new Log();

        if (currentUser == null) {
            log.setUserId(0);
            log.setUsername("NOUSERT");
        } else {
            log.setUserId(currentUser.getId());
            log.setUsername(currentUser.getUsername());
        }
        log.setIpAddress(getIpAddress(request));
        log.setType(type);
        log.setTitle(title);
        log.setContent(content);
        logService.addLog(log);

    }

    /**
     * new PageData对象
     *
     * @return
     */
    public PageData getPageData() {
        return new PageData(this.getRequest());
    }

    /**
     * 得到request对象
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 获得当前用户
     *
     * @return
     */
    public User findCurrentUser() {

        //获得当前登陆用户的username
        String username = request.getRemoteUser();

        if (!StringUtils.isEmpty(username)) {
            User currentUser = userService.findUserByUserName(username);
            return currentUser;
        }
        return null;

    }

    /**
     * 做 空判断
     *
     * @param param
     * @return
     */
    public String isEmpty(String param) {
        if (StringUtils.isEmpty(param)) {
            return null;
        }
        return param;
    }

}